package cn.com.jonpad.demo03j_jpa.service;

import cn.com.jonpad.demo03j_jpa.entity.QCity;
import cn.com.jonpad.demo03j_jpa.entity.QHotel;
import cn.com.jonpad.demo03j_jpa.repository.CityRepository;
import com.querydsl.core.Tuple;
import com.querydsl.jpa.impl.JPAQuery;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.querydsl.core.types.Predicate;

import javax.persistence.EntityManager;
import java.util.List;

/**
 * @author Jon Chan
 * @date 2019/1/21 17:37
 */
@Service
public class CityAndHotelService {
    @Autowired
    private CityRepository cityRepository;
    @Autowired
    private EntityManager entityManager;

    /**
     * 关联查询示例,查询出城市和对应的旅店
     * @param predicate
     * @return
     */
    public List<Tuple> findCityAndHotel(Predicate predicate){
        JPAQueryFactory queryFactory = new JPAQueryFactory(entityManager);

        JPAQuery<Tuple> jpaQuery = queryFactory.select(QCity.city, QHotel.hotel)
                .from(QCity.city)
                .leftJoin(QHotel.hotel)
                .on(QHotel.hotel.city.longValue().eq(QCity.city.id.longValue()));
        jpaQuery.where(predicate);
        return jpaQuery.fetch();
    }

}
